<?php

use Illuminate\Database\Capsule\Manager as DB;

class TaskController extends CommonController
{
    protected $authExcept = ['list', 'detail'];

    // 查询任务列表
    public function listAction()
    {
        $params = $this->get();
        $is_page = true;
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;
        $query =taskModel::query()
            ->where('status', 1);
        $total = $query->count();
        if ($is_page) {
            $data = $query->offset(($page - 1) * $per_page)->limit($per_page)->get();
        } else {
            $data = $query->get();
        }

        $result = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];
        json(['code' => 1, 'msg' => '任务列表', 'data' => $result]);
    }

    // 我的任务列表
    public function detailAction()
    {
        $params = $this->get();
        $result =taskModel::query()->where('id', $params['id'])->first();
        json(['code' => 1, 'msg' => '任务详情', 'data' => $result]);
    }

    // 我的任务列表
    public function mytaskAction()
    {
        $params = $this->get();
        $is_page = true;
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;
        $query =taskmemberModel::with(['task'])->where('member_id', $this->user->id);
        $total = $query->count();
        if ($is_page) {
            $data = $query->offset(($page - 1) * $per_page)->limit($per_page)->get();
        } else {
            $data = $query->get();
        }

        $result = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];
        json(['code' => 1, 'msg' => '我的任务列表', 'data' => $result]);
    }

    public function receiveTaskAction()
    {
        $input = $this->postData;
        $roles = [
            'task_id' => ['roles'=>'required|exists:task.id', 'msg' => '任务'],
        ];
        Validate::check($input, $roles);
        $task = taskModel::query()->find($input['task_id']);
        if($task->status != 1){
            throw new Exception("任务活动已下线");
        }
        if( taskmemberModel::query()->where('member_id', $this->user->id)->where('task_id', $input['task_id'])->exists()){
            throw new Exception("任务已领取");
        }
        if( !in_array($this->user->level, explode(',', $task->task_levels)) ){
            throw new Exception("当前级别不可领取此任务");
        }
        if( $task->special_ids!='' && !in_array($this->user->id, preg_split("/[,，]/", $task->special_ids)) ){
            throw new Exception("当前会员不可领取此任务");
        }
        $mem = memberModel::query()->where('id', $this->user->id)->first();
        $team_child_agent_all_counter = DB::select('SELECT count(*) as cnt from cs_member where level>1 and id in (SELECT children_id from cs_member_children where `member_id`=:id) ', ['id' => $mem->id]);
        $team_child_agent_direct_counter = DB::select('SELECT count(*) as cnt from cs_member where level>1 and id in (SELECT children_id from cs_member_children where level=1 and `member_id`=:id) ', ['id' => $mem->id]);
        $team_child_agent = [];
        $levels = agentlevelModel::get();
        foreach ($levels as $level) {
            $counter = DB::select('SELECT count(*) as cnt from cs_member where level=:level and id in (SELECT children_id from cs_member_children where `member_id`=:id) ',
                ['level' => $level->level,
                    'id'    => $mem->id]);
            $cnt     = $counter[0]->cnt;
            array_push($team_child_agent,  [
                'level' => $level->level,
                'name'  => $level->name,
                'count' => $cnt
            ]);
        }
        $status = [
            'team_consume'  =>  $mem->team_consume,
            'total_consume' =>  $mem->total_consume,
            'team_child'    =>  memberchildrenModel::query()->where('member_id', $mem->id)->count(),
            'team_child_direct'=>   memberchildrenModel::query()->where('member_id', $mem->id)->where('level', 1)->count(),
            'team_child_agent_all'  => $team_child_agent_all_counter[0]->cnt,
            'team_child_agent_direct'=>$team_child_agent_direct_counter[0]->cnt,
            'team_child_agent'=> $team_child_agent,
        ];
        $taskMem = [
            'member_id' =>  $this->user->id,
            'task_id'   =>  $input['task_id'],
            'task_name'     =>  $task->name,
            'finish_rules'  =>  $task->finish_rules,
            'reward_duration'   =>$task->reward_duration,
            'reward_rules'  =>  $task->reward_rules,
            'task_expired_at'    =>  date('Y-m-d H:i:s', strtotime("+{$task->task_duration} day")),
            'before_member_status'  =>  json_encode($status, JSON_UNESCAPED_UNICODE),
            'after_member_status'   =>  '',
            'task_status'           =>  0,
            'created_at'            =>  date('Y-m-d H:i:s')
        ];
        taskmemberModel::insert($taskMem);
        json(['code' => 1, 'msg' => '领取任务成功']);
    }

}
